<script setup lang="ts">
import { getTypeList } from '@/api/productType';
import { http } from '@/services/http';
import type { Menu, PageDto, ProductInfo, ResponseData } from '@/types';
import { toPrice } from '@/utils/convert';
import Main from './Main.vue';
import { onMounted, onUnmounted, reactive, ref } from 'vue';
import { Waterfall } from 'vue-waterfall-plugin-next';
import 'vue-waterfall-plugin-next/dist/style.css';
import eventBus from 'vue3-eventbus';
import { getClientHeight, getScrollHeight, getScrollTops } from '@/utils/screenUtil';

const topLoading = ref(false);

const activeMenu = ref('');
const menuList = ref<Menu[]>([
  {
    id: '',
    crteateTime: 0,
    updateTime: 0,
    typeCode: '',
    typeName: '全部',
  },
]);
const noMore = ref(false);
const busy = ref(false);
const productId = ref('');
const mainShow = ref(false);
const toMain = (id: string) => {
  mainShow.value = true;
  productId.value = id;
};

const productList = ref<ProductInfo[]>([]);

const page_param = reactive<PageDto>({
  pageNumber: 1,
  pageSize: 15,
  typeCode: '',
  key: '',
});

const changeMenu = (item: Menu) => {
  page_param.pageNumber = 1;
  productList.value = [];
  busy.value = false;
  // if (item.typeCode === '000') {
  //   page_param.typeCode = '';
  //   activeMenu.value = item.typeCode;
  //   getProductList();
  // } else {
  page_param.typeCode = item.typeCode;
  activeMenu.value = item.typeCode;
  getProductList();
  // }
};

const getProductList = () => {
  http
    .get<ResponseData>('/product/info/page', page_param)
    .then((res) => {
      const list = res.result;
      if (list.length === 0) {
        // 一秒后设置为 true
        setTimeout(() => {
          noMore.value = true;
        }, 2000);
      } else {
        list.forEach((item: { image: string }) => {
          if (item.image) {
            item.image = JSON.parse(item.image)[0];
          }
        });
        productList.value.push(...list);
        console.log(152, productList.value);

        busy.value = false;
      }
      topLoading.value = false;
    })
    .catch((error) => {
      console.error('Error fetching product list:', error);
    });
};
const getMenuList = () => {
  getTypeList().then((res) => {
    menuList.value.push(...res.result);
    console.log(198, menuList.value);
  });
};

const closeMain = () => {
  mainShow.value = false;
};

const handleKeyChanged = (newKey: string) => {
  page_param.pageNumber = 1;
  busy.value = true;
  productList.value = [];
  page_param.key = newKey;
  getProductList();
};

const windowScroll = () => {
  const scrollTop = getScrollTops();
  const clientHeight = getClientHeight();
  const scrollHeight = getScrollHeight();
  if (scrollTop + clientHeight >= scrollHeight - 1) {
    if (!busy.value) {
      busy.value = true;
      page_param.pageNumber += 1;
      getProductList();
    }
  }
};

onMounted(() => {
  window.addEventListener('scroll', windowScroll, true);
  eventBus.on('keyChanged', handleKeyChanged);
  getProductList();
  getMenuList();
});

onUnmounted(() => {
  eventBus.off('keyChanged', handleKeyChanged);
  window.removeEventListener('scroll', windowScroll);
});
</script>

<template>
  <div class="feeds-page">
    <!--top-->
    <div class="channel-container">
      <div class="scroll-container channel-scroll-container">
        <div class="content-container" style="margin-left: 3vh">
          <div
            class="channel"
            :class="{ active: activeMenu === item.typeCode }"
            v-for="item in menuList"
            :key="item.typeCode"
            @click="changeMenu(item)"
          >
            {{ item.typeName }}
          </div>
        </div>
      </div>
    </div>

    <!--loading-->
    <div class="loading-container"></div>
    <!-- feed container -->
    <div class="feeds-container">
      <!-- <el-backtop target=".feeds-container" @click="refresh">aaa</el-backtop> -->
      <div class="feeds-loading-top" v-show="topLoading">
        <el-icon><Loading /></el-icon>
      </div>
      <Waterfall
        :list="productList"
        :width="230"
        :hasAroundGutter="false"
        style="max-width: 1260px"
        :delay="1000"
        :animationEffect="'animate__zoomIn'"
      >
        <template #default="{ item }">
          <div class="card" @click="toMain(item.id)">
            <el-image style="border-radius: 10px; width: 230px" :src="item.image" fit="cover"></el-image>
            <div class="footer">
              <a class="title"
                ><span>{{ item.title }}</span></a
              >
              <div class="price">
                <span>￥{{ toPrice(item.price) }}</span>
                <span
                  style="
                    margin-left: 5px;
                    font-size: 11px;
                    color: #9e9e9e;
                    font-weight: normal;
                    text-decoration: line-through;
                  "
                  >￥{{ toPrice(item.price) }}</span
                >
                <span style="margin-left: 5px; font-size: 11px; color: #9e9e9e; font-weight: normal">{{
                  item.city
                }}</span>
                <span style="margin-left: 5px; font-size: 11px; color: #9e9e9e; font-weight: normal">{{
                  item.postType === 0 ? '邮寄' : '自提'
                }}</span>
              </div>
              <div class="author-wrapper">
                <a class="author">
                  <img class="author-avatar" :src="item.avatar" />
                  <span class="name">{{ item.nickName }} </span>
                </a>
                <span class="like-wrapper"
                  ><i class="el-icon-thumb"></i>
                  <span class="count">{{ item.likeCount }}人想要</span>
                </span>
              </div>
            </div>
          </div>
        </template>
      </Waterfall>
      <!--loading-->
      <el-collapse-transition>
        <div class="feeds-loading" v-show="busy && !noMore">
          <span style="text-align: center; color: #cacdd5; font-size: 12px">加载中</span><el-icon><Loading /></el-icon>
        </div>
      </el-collapse-transition>
      <div v-show="noMore" style="text-align: center; color: #cacdd5; font-size: 12px; margin: 3vh">没有更多了</div>
    </div>
    <Transition name="fade">
      <Main @main_close="closeMain" v-if="mainShow" :productId="productId"></Main>
    </Transition>
  </div>
</template>

<style lang="less" scoped>
.fade-enter-active,
.fade-leave-active {
  transition: all 0.5s ease-in;
}

.fade-enter-from,
.fade-leave-to {
  transform: scale(0.1);
}

.feeds-page {
  flex: 1;
  padding: 0 24px;
  padding-top: 72px;

  .channel-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    user-select: none;
    -webkit-user-select: none;

    .channel-scroll-container {
      backdrop-filter: blur(20px);
      background-color: transparent;
      width: calc(100vw - 24px);

      position: relative;
      overflow: hidden;
      display: flex;
      user-select: none;
      -webkit-user-select: none;
      align-items: center;
      font-size: 16px;
      color: rgba(51, 51, 51, 0.8);
      height: 40px;
      white-space: nowrap;
      height: 72px;

      .content-container::-webkit-scrollbar {
        display: none;
      }

      .content-container {
        display: flex;
        overflow-x: scroll;
        overflow-y: hidden;
        white-space: nowrap;
        color: rgba(51, 51, 51, 0.8);

        .active {
          font-weight: 600;
          background: rgba(0, 0, 0, 0.03);
          border-radius: 999px;
          color: #333;
        }

        .channel {
          height: 40px;
          display: flex;
          justify-content: center;
          align-items: center;
          padding: 0 16px;
          cursor: pointer;
          -webkit-user-select: none;
          user-select: none;
        }
      }
    }
  }

  .feeds-container {
    position: relative;
    transition: width 0.5s;
    margin: 0 auto;
    overflow-y: auto;
    height: 77vh;

    .feeds-loading {
      text-align: center;
    }

    .feeds-loading-top {
      line-height: 6vh;
      height: 6vh;
    }

    .feeds-loading-top {
      -webkit-animation: move_1 0.5s;
    }

    @-webkit-keyframes move_1 {
      0% {
        -webkit-transform: translateY(-20px);
        opacity: 0;
      }
    }

    .noteImg {
      width: 240px;
      max-height: 300px;
      object-fit: cover;
      border-radius: 8px;
    }

    .card {
      position: relative;
      cursor: pointer;

      .top-tag-area {
        position: absolute;
        left: 12px;
        top: 12px;
        z-index: 4;

        .top-wrapper {
          background: #ff2442;
          border-radius: 999px;
          font-weight: 500;
          color: #fff;
          line-height: 120%;
          font-size: 12px;
          padding: 5px 8px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }

    .footer {
      padding: 12px;

      .title {
        margin-bottom: 8px;
        word-break: break-all;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        font-weight: 500;
        font-size: 14px;
        line-height: 140%;
        color: black;
      }

      .price {
        margin-bottom: 8px;
        word-break: break-all;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        font-weight: bolder;
        font-size: 16px;
        color: red;
        line-height: 140%;
      }

      .author-wrapper {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 20px;
        color: rgba(51, 51, 51, 0.8);
        font-size: 12px;
        transition: color 1s;

        .author {
          display: flex;
          align-items: center;
          color: inherit;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          margin-right: 12px;

          .author-avatar {
            margin-right: 6px;
            width: 20px;
            height: 20px;
            border-radius: 20px;
            border: 1px solid rgba(0, 0, 0, 0.08);
            flex-shrink: 0;
            object-fit: cover;
          }

          .name {
            color: #9e9e9e;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }

        .like-wrapper {
          position: relative;
          display: flex;
          align-items: center;

          .count {
            color: #9e9e9e;
            margin-left: 2px;
          }
        }
      }
    }
  }

  .floating-btn-sets {
    position: fixed;
    display: flex;
    flex-direction: column;
    width: 40px;
    grid-gap: 8px;
    gap: 8px;
    right: 24px;
    bottom: 24px;

    .back-top {
      width: 40px;
      height: 40px;
      background: #fff;
      border: 1px solid rgba(0, 0, 0, 0.08);
      border-radius: 100px;
      color: rgba(51, 51, 51, 0.8);
      display: flex;
      align-items: center;
      justify-content: center;
      // transition: background 0.2s;
      cursor: pointer;
    }

    .reload {
      width: 40px;
      height: 40px;
      background: #fff;
      border: 1px solid rgba(0, 0, 0, 0.08);
      box-shadow:
        0 2px 8px 0 rgba(0, 0, 0, 0.1),
        0 1px 2px 0 rgba(0, 0, 0, 0.02);
      border-radius: 100px;
      color: rgba(51, 51, 51, 0.8);
      display: flex;
      align-items: center;
      justify-content: center;
      //transition: background 0.2s;
      cursor: pointer;
    }
  }
}
</style>
